
require 'csv'
#require 'pp'

module TheFox
	module VieTra
		
		class CsvFile
			
			def initialize(file_path)
				@file_path = file_path
				@has_data = false
				@data = []
				@cols_needed = []
			end
			
			def read
				if !@has_data
					@has_data = true
					
					#puts "read"
					fill_cols_needed
					
					#pp @cols_needed
					
					csv_options = {
						:col_sep => ';',
						#:row_sep => "\n",
						:headers => true,
						#:return_headers => false,
						:return_headers => true,
						:skip_blanks => true,
						:encoding => 'UTF-8',
					}
					
					CSV.foreach(@file_path, csv_options) do |csv_row|
						#puts "#{row.to_a}"
						
						row = @cols_needed.map{ |col_name| [col_name, csv_row.field(col_name)] }.to_h
						#pp row
						@data << row
					end
				end
			end
			
			def search_cols
				[]
			end
			
			def data_cols
				[]
			end
			
			def fill_cols_needed
				if @cols_needed.count == 0
					@cols_needed += search_cols
					@cols_needed += data_cols
				end
			end
			
			def search(str)
				read
				
				str_re = Regexp.new(str, Regexp::IGNORECASE)
				
				found_rows = []
				@data.each do |row|
					found = @cols_needed.map{ |col_name| row[col_name] }.select{ |col_val|
						!str_re.match(col_val).nil?
					}
					if found.count > 0
						found_row = @cols_needed.map{ |col_name| [col_name, row[col_name]] }
						found_rows << found_row.to_h
					end
				end
				found_rows
			end
			
		end
		
	end
end
